package com.itheima.itheima_health.service.Impl;

import com.itheima.itheima_health.constant.MessageConstant;
import com.itheima.itheima_health.exception.BaseException;
import com.itheima.itheima_health.mapper.BookingMapper;
import com.itheima.itheima_health.mapper.CheckitGroupMapper;
import com.itheima.itheima_health.mapper.SetmealMapper;
import com.itheima.itheima_health.pojo.CheckGroup;
import com.itheima.itheima_health.pojo.CheckItem;
import com.itheima.itheima_health.pojo.Setmeal;
import com.itheima.itheima_health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CheckitGroupMapper checkitGroupMapper;
    @Autowired
    private BookingMapper bookingMapper;
    @Override
    public List<Setmeal> getAllSetmeal() {
        List<Setmeal> setmealList = setmealMapper.getAllSetmeal();
        return setmealList;
    }
    @Override
    public Setmeal findById(Integer id) {
        try{
            //1.查询套餐数据
            Setmeal setmeal = setmealMapper.findById(id);

            //2.查询套餐的检查组

            //查询套餐的检查组id
            Integer[] checkGroupIds =  setmealMapper.checkGroupIdsgetBysetmealId(id);

            //根据检查组id查询检查项
            List<CheckGroup> checkGroupList = new ArrayList<>();
            for (Integer checkGroupId : checkGroupIds) {
                //类型强转
                Long Groupid = Long.valueOf(checkGroupId);
                //根据检查组id查询检查组数据
                CheckGroup checkGroup = checkitGroupMapper.CheckitemGroupfindById(Groupid);

                //根据检查组id查询检查项ids
                List<Integer> checkItemIds = checkitGroupMapper.findCheckitemgroupIdBycheckitemId(Groupid);

                //根据检查项id查询检查项数据
                List<CheckItem> checkItemList = new ArrayList<>();
                for (Integer checkItemId : checkItemIds) {
                    //类型强转
                    Long ItemId = Long.valueOf(checkItemId);
                    CheckItem checkItem = bookingMapper.CheckitemTergetByid(ItemId);
                    checkItemList.add(checkItem);
                }
                checkGroup.setCheckItems(checkItemList);
                //3.查询检查组的检查项
                checkGroupList.add(checkGroup);
            }

            //检查组 封装
            setmeal.setCheckGroups(checkGroupList);
            return setmeal;
        }catch (Exception e){
            throw new BaseException(MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}
